import json
import random
import threading
import time
from xmlrpc import client

from requests import get
from flask import Flask,render_template,redirect,request

flask_app = Flask(
    import_name=__name__,
    static_url_path="/static",#静态资源路径
    static_folder="ui",#静态资源文件夹
    template_folder="ui/html"#模板路径
)

ALL_FONTS = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

#创建随机数
def createRandomNum():
    result = ""
    for i in range(8):
        result += str(ALL_FONTS[random.randint(0,len(ALL_FONTS)-1)])
    return result

LOCK = threading.Lock()
ALL_ROOMNUM_PW = {} # key room num value pw

@flask_app.route("/initroom")
def initroom():
    roomnum = ""
    password = ""
    #room num 为空  或者 roomnum 已经存在 需要创建房间号和密码
    LOCK.acquire()
    while roomnum == "" or roomnum in ALL_ROOMNUM_PW.keys():
        roomnum = createRandomNum()
        password = createRandomNum()
    ALL_ROOMNUM_PW[roomnum] = password
    LOCK.release()
    return redirect("/index/"+roomnum+"/"+password)


@flask_app.route("/")
def home():
    return render_template("home.html")

@flask_app.route("/index/<roomnum>/<password>")
def index(roomnum, password):
    return render_template("index.html",roomnum=roomnum, password=password)

@flask_app.route("/login",methods = ["post"])
def login():
    roomnum = request.form.get("roomnum")
    password = request.form.get("password")
    #login successfully
    LOCK.acquire()
    if roomnum in ALL_ROOMNUM_PW.keys() and password == ALL_ROOMNUM_PW[roomnum]:
        return redirect("/index/"+roomnum+"/"+password)
    else:
        return redirect("/")
    LOCK.release()

#访问WS服务器中的线程上的flask服务
def cleanDisableRoom(server: client.ServerProxy):
    print("scan ws server rooms theading start...")
    while 1:
        print("scan ws server rooms")
        LOCK.acquire()
        for roomnum in list(ALL_ROOMNUM_PW.keys()):
            # http call
            # response = get("http://localhost:8887/personcount/{}".format(roomnum))
            #rpc call
            result_dict = server.personcount(roomnum)
            if result_dict != None:
                if (c := result_dict["count"]) > 0:
                    print("room num:{} 目前有{}用户".format(roomnum, c))
                    pass
                else:
                    del ALL_ROOMNUM_PW[roomnum]
                    print(f"clean room,room number:{roomnum}")
        LOCK.release()
        time.sleep(4)

if __name__ == "__main__":
    server = client.ServerProxy("http://localhost:8848")
    threading.Thread(target=cleanDisableRoom, args=(server,)).start()
    flask_app.run("0.0.0.0", 8888)

    #likepeakapp
    #gitee.com/luoruofeng/chatroom